import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import { useMapStoreHook } from "@/store/modules/map";
import elForm from '../form.vue'

import { crossList, addCross, updateCross, delCross } from '@/utils/api/dispatch/cross'
import { GetAllStation } from '@/utils/api/dispatch/station'
import ReCol from '@/components/ReCol';

export function useDept() {
    const form = reactive({
        name: "",
        pageNumber: 0,
        pageSize: 200,
        sortName: "createtime",
        sortType: 0
    });
    const incrementalName = ref(null);

    const pureMap = useMapStoreHook()
    const formRef = ref();
    var dataList = ref([]);
    var agvCrossSwitch = ref(false)
    var expandOpen = ref(false)
    const dataListDeep = ref([])
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 100,
        currentPage: 1,
        background: true
    });

    // 状态Select
    const SelectStatusOptions = reactive([
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' },
        { value: 2, label: '锁定' },
    ])

    // 站点Select
    const stationOptions = ref([])

    // 状态
    function formatStatus(status) {
        const stateMap = {
            1: '启用',
            0: '禁用',
            2: '锁定'
        }
        return stateMap[status]
    }
    // 类型
    function formatType(status) {
        const stateMap = {
            // 0: '站点交管',
            1: '唯一区域交管',
            2: '巷道区域交管',
            3: '公共区域交管',
            4: '可穿行交管',
            5: '巷道多车交管',
        }
        return stateMap[status]
    }

    const columns: TableColumnList = [
        {
            type: "expand",
            slot: "expand"
        },
        {
            label: "类型",
            prop: "type",
            width: 100,
            cellRenderer: ({ row, props }) => (
                <span>
                    {formatType(row.type)}
                </span>
            )
        },
        {
            label: "状态",
            prop: "status",
            width: 60,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.status)}>
                    {formatStatus(row.status)}
                </el-tag>
            )
        },
        {
            label: "交管名称",
            prop: "name",
            width: 90,
            align: "left",
            sortable: true
        },
        // {
        //   label: `集合`,
        //   prop: "stationNameList",
        //   align: "left",
        //   cellRenderer: ({ row, props }) => (
        //     <div>
        //       {
        //         !row.type ? 
        //         row.stationNameList.map((v,i)=>(
        //           <el-tag size={props.size} type="success"  key={v.id} style="margin-left:10px;">
        //             {v}
        //           </el-tag>
        //         ))
        //         :
        //         row.stationList.map((v,i)=>(
        //           <el-tag size={props.size} type="success"  key={v.id} style="margin-left:10px;">
        //             X:{v.x}, Y:{v.y}
        //           </el-tag>
        //        ))
        //       }
        //     </div>
        //   )
        // },
        {
            label: "操作",
            fixed: "right",
            slot: "operation"
        }
    ]

    async function onSearch() {
        loading.value = true;
        const { Content } = await crossList(form);
        // 根据name进行从小到大排序
        Content.Results.sort((a, b) => {
            const numA = Number(a.name);
            const numB = Number(b.name);
            return numA - numB;
        });
        let newData = Content.Results;
        // 获取最后一个元素的name
        pureMap.changeName(newData[newData.length - 1].name)
        // console.log('hook初始化=>', pureMap.incrementalName);


        dataList.value = newData;
        dataListDeep.value = newData
        pagination.total = Content.TotalCount;
        pagination.pageSize = Content.PageSize;
        pagination.currentPage = Content.PageNumber + 1;

        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 交管列表切换
    // 定义一个名为 crossSearch 的函数，用于处理交叉搜索逻辑
    function crossSearch() {
        // 检查 agvCrossSwitch 的值，如果为 true，则执行以下逻辑
        if (agvCrossSwitch.value) {
            // 将 dataListDeep 的值赋给 dataList，恢复到初始数据状态
            dataList.value = dataListDeep.value
            // 将 expandOpen 设置为 false，表示不展开
            expandOpen.value = false
        } else {
            // 定义一个空数组 agvCross，用于存储过滤后的数据
            var agvCross = []
            // 从 pureMap.scoketData.CrossMsgData 中过滤出 AgvList 不为空的项
            const scoketCross = pureMap.scoketData.CrossMsgData.filter(v => {
                return v.AgvList.length !== 0
            })

            // 遍历过滤后的 scoketCross 数组
            scoketCross.forEach(j => {
                // 在 dataList 中查找与 scoketCross 中 CrossId 相同的项
                const data = dataList.value.find(v => { return v.id === j.CrossId })
                // 将找到的项添加到 agvCross 数组中
                agvCross.push(data)
            })
            // 将 agvCross 的值赋给 dataList，更新显示的数据
            dataList.value = agvCross
            // 将 expandOpen 设置为 true，表示展开
            expandOpen.value = true
        }
        // 切换 agvCrossSwitch 的值，用于下次调用时切换状态
        agvCrossSwitch.value = !agvCrossSwitch.value
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        if (row?.stationids) {
            row.stationids = row.stationids.split(',').map(v => { return Number(v) })
        }
        if (row?.parallestaids) row.parallestaids = row.parallestaids.split(',').map(v => { return Number(v) })

        addDialog({
            title: `${title}交管`,
            props: {
                formInline: {
                    name: row?.name ?? "",
                    status: row?.status ?? 1,
                    note: row?.note ?? "",
                    type: row?.type ?? null,
                    stationids: row?.stationids ?? null,
                    parallestaids: row?.parallestaids ?? [],
                    stationList: row?.stationList ?? [{
                        "crossid": 0
                    }]
                },
                SelectStatusOptions: SelectStatusOptions || [],
                stationOptions: stationOptions.value || []
            },
            width: "35%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(elForm, { ref: formRef }),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    message(`您${title}了交管名称为${curData.name}的这条数据`, {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        // 表单规则校验通过
                        curData.stationids = curData.stationids.toString()
                        if (title === "新增") {
                            addCross(curData).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else {
                            let data = Object.assign(curData, { id: row.id })
                            updateCross(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    // 删除
    function handleDelete(row) {
        ElMessageBox.confirm(
            `是否确认删除名称为${row.name}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            delCross(row.id).then(res => {
                if (res.Code === 0) {
                    message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onMounted(async () => {
        onSearch()

        // 站点下拉
        const { Content } = await GetAllStation()
        stationOptions.value = Content
    })

    return {
        columns,
        loading,
        dataList,
        openDialog,
        handleDelete,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange,
        crossSearch,
        expandOpen,
        agvCrossSwitch,
        incrementalName
    }
}